package com.monitor.controller;

import com.monitor.commons.CreateImageCode;
import com.monitor.commons.IdGen;
import com.monitor.commons.SkJsonResult;
import com.monitor.commons.StringUtil;
import com.monitor.dto.LoginDTO;
import com.monitor.exception.ExceptionMessage;
import com.monitor.modelExt.AdminExt;
import com.monitor.pubInter.IBaseService;
import com.monitor.pubInter.exception.BusinessException;
import com.monitor.pubInter.exception.SkException;
import com.monitor.service.IAdminService;
import com.monitor.web.common.token.AdminToken;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/")
@RestController(value = "indexController")
public class IndexController extends ApiManageController {
    @Autowired
    private IAdminService adminService;

    @Override
    public IBaseService getBaseService() throws SkException {
        return null;
    }


    @ApiOperation(value = "生成图片验证码", notes = "生成图片验证码", httpMethod = "GET")
    @GetMapping("imageCode")
    public void createImageCode(HttpServletRequest request, HttpServletResponse response, @ApiParam("时间戳") @RequestParam(required = false) String codeKey) throws Exception {


        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        CreateImageCode vCode = new CreateImageCode(150, 50, 4, 3);

        getRedisUtil().set(codeKey, vCode.getCode());


        vCode.write(response.getOutputStream());


    }


    @PostMapping("loginAction")
    public SkJsonResult loginAction(@RequestBody LoginDTO dto, HttpServletResponse response) throws SkException {

        String imageCode = (String) getRedisUtil().get(dto.getCodeKey());
        getRedisUtil().del(dto.getCodeKey());
        if (isImgCodeVerification()) {
            if (StringUtil.isEmpty(dto.getImageCode()) || !dto.getImageCode().equalsIgnoreCase(imageCode)) {
                throw new BusinessException(ExceptionMessage.IMAGE_CODE_ERROR);
            }
        }
        AdminExt adminExt = adminService.loginByUsernameAndPsw(dto.getUsername(), dto.getPassword());
        AdminToken adminToken=new AdminToken();
        adminToken.setRedisKey(IdGen.uuid());
        adminToken.setAdminId(adminExt.getId());
        adminToken.setUsername(adminExt.getUsername());

        getJwtsUtil().setAdminToken(adminToken,response);

        return SkJsonResult.ok().setData(adminExt);
    }


}
